package com.rtwo.shiro.realm;

import com.rtwo.shiro.entity.ShUser;
import com.rtwo.shiro.service.ShUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Created by hasee on 2017/6/4.
 */
@Component
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private ShUserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        ShUser user = (ShUser) principalCollection.getPrimaryPrincipal();
        if(user!=null){
            for (String permission : userService.getPermissionsByUsername(user.getUsername())) {
                authorizationInfo.addStringPermission(permission);
            }
            return authorizationInfo;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        if(username!=null&&!"".equals(username)){
            ShUser user = userService.findUserByUsername(username);
            if(user!=null){
                return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),getName());
            }
        }
        return null;
    }
}


